{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 109,
   "id": "a9f68366",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/latex": [
       "$\\displaystyle 1.45604740209448 \\cdot 10^{-5}$"
      ],
      "text/plain": [
       "1.45604740209448e-5"
      ]
     },
     "execution_count": 109,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import sympy\n",
    "\n",
    "st = 'x1 x2 x3 x4'\n",
    "li = st.split(' ')\n",
    "\n",
    "x1,x2,x3,x4 = sympy.symbols(st)\n",
    "\n",
    "# 构造函数\n",
    "\n",
    "f = (x1+10 * x2) ** 2 + 5 * (x3-x4)**2 + (x2-2 * x3) ** 4 + 10 * (x1-x4) ** 4\n",
    "\n",
    "var_list = list(sympy.sympify(x) for x in li)\n",
    "\n",
    "# 构造梯度矩阵\n",
    "\n",
    "grad_f = []\n",
    "for i in var_list:\n",
    "    grad_f.append(f.diff(i, 1))\n",
    "grad_f = sympy.Matrix(grad_f)\n",
    "\n",
    "# 构造黑塞矩阵\n",
    "\n",
    "F_f = []\n",
    "\n",
    "for i in var_list:\n",
    "    col = []\n",
    "    for j in var_list:\n",
    "        col.append(f.diff(i, j))\n",
    "    F_f.append(col)\n",
    "F_f = sympy.Matrix(F_f)\n",
    "\n",
    "# 开始迭代\n",
    "\n",
    "n_x = None\n",
    "x = np.array([3, -1, 0, 1])\n",
    "x_val = {sympy.sympify(k) : v for k, v in zip(li, x)}\n",
    "for i in range(10):\n",
    "    if n_x is  None:\n",
    "        n_x = x.reshape(4, 1) - F_f.subs(x_val).inv() * grad_f.subs(x_val)\n",
    "        x_val = {sympy.sympify(k) : v for k, v in zip(li, n_x)}\n",
    "    else:\n",
    "        n_x = n_x - F_f.subs(x_val).inv() * grad_f.subs(x_val)\n",
    "        x_val = {sympy.sympify(k) : v for k, v in zip(li, n_x)}\n",
    "sympy.N(f.subs(x_val))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
